package net.qhzw.geologr5.gis.service.system.service;

import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.common.framework.utils.StringUtils;
import net.qhzw.geologr5.gis.service.system.entity.Dict;
import net.qhzw.geologr5.gis.service.system.mapper.DictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DictService {


    @Autowired
    private DictMapper dictMapper;


    @Transactional(rollbackFor = Exception.class)
    public JsonResult deleteByIds(Integer[] dicIds) {
        try {
            List<Integer> list = Arrays.asList(dicIds);
            int row = dictMapper.deleteBatchIds(list);
            return JsonResult.success();
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }
    }

    /***
     * 添加字典项
     * @param entity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult edit(Dict entity) {

        try {
            if (StringUtils.isEmpty(entity.getCode())) {
                return JsonResult.error("字典值不能为空");
            }
            if (entity.getId() == null || entity.getId() <= 0) {
                //新增
                entity.setMark(1);
                entity.setCreateTime(new Date());
                Integer count = dictMapper.findCountByNameAndCode(entity.getName(), entity.getCode());
                if (count > 0) {
                    return JsonResult.error("字典名称不能重复");
                }
                int row = dictMapper.insert(entity);
                this.result(row, "添加失败");
            }
            entity.setUpdateTime(new Date());
            int row = dictMapper.updateById(entity);
            Integer count = dictMapper.findCountByNameAndCode(entity.getName(), entity.getCode());
            if (count > 1) {
                throw new RuntimeException("字典名称不能重复");
            }
            return JsonResult.success();
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }
    }

    /***
     * 判断集合存在重复数据
     * @param list
     * @return
     */
    private Boolean isRepeat(List<String> list) {
        Set<String> set = new HashSet<>(list);
        if (set.size() == list.size()) {
            return true;
        }
        return false;
    }


    private JsonResult result(Integer row, String msg) {
        if (row > 0) {
            return JsonResult.success();
        }
        return JsonResult.error(msg);
    }
}
